package com.hellobike.haxing.modules.wms.facade.impl;

import com.hellobike.haxing.modules.product.entity.Sku;
import com.hellobike.haxing.modules.product.service.ISkuService;
import com.hellobike.haxing.modules.wms.constans.WmsConstans;
import com.hellobike.haxing.modules.wms.dto.StockChangeDto;
import com.hellobike.haxing.modules.wms.entity.*;
import com.hellobike.haxing.modules.wms.enums.*;
import com.hellobike.haxing.modules.wms.exception.WmsServiceException;
import com.hellobike.haxing.modules.wms.facade.WmsShippingFacade;
import com.hellobike.haxing.modules.wms.facade.WmsStockFacade;
import com.hellobike.haxing.modules.wms.service.*;
import com.hellobike.haxing.modules.wms.utils.ListUtil;
import com.hellobike.haxing.modules.wms.utils.WmsCodeGeneratorUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Component("wmsShippingFacade")
public class WmsShippingFacadeImpl implements WmsShippingFacade {

    @Autowired
    private ICarOutService carOutService;
    @Autowired
    private IShippingHeaderService shippingHeaderService;
    @Autowired
    private IShippingDetailService shippingDetailService;
    @Autowired
    private IDeliveryOrderHeaderService deliveryOrderHeaderService;
    @Autowired
    private IDeliveryOrderBoxService deliveryOrderBoxService;
    @Autowired
    private IDeliveryOrderDetailService deliveryOrderDetailService;
    @Autowired
    private IStockPickService stockPickService;
    @Autowired
    private WmsStockFacade wmsStockFacade;
    @Autowired
    private ICodeHolderPointService codeHolderPointService;
    @Autowired
    private IReturnWarehouseDetailService returnWarehouseDetailService;
    @Autowired
    private IReturnWarehouseHeaderService returnWarehouseHeaderService;
    @Autowired
    private ISkuService skuService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addShipping(ShippingHeader header, List<Long> deliveryIds, Long warehouseId, Integer userId) throws WmsServiceException {
        if (header == null) {
            throw new WmsServiceException("参数缺失");
        }
        String carOutCode = header.getCarOutCode();
        if (StringUtils.isNotEmpty(carOutCode)) {
            CarOut carOut = carOutService.getByCarOutCode(carOutCode);
            if (carOut == null) {
                throw new WmsServiceException("出车单不存在");
            }
            if (!CarOutStatusEnum.INIT.getValue().equals(carOut.getCarOutStatus())) {
                throw new WmsServiceException("出车单已使用");
            }
            if (!CarOutTypeEnum.SH.getValue().equals(carOut.getCarOutType())) {
                throw new WmsServiceException("出车单类型不是送货");
            }
            header.setCarOutId(carOut.getId());
            carOut.setCarOutStatus(CarOutStatusEnum.WAIT_OUT.getValue());
            carOutService.updateById(carOut);
        }
        header.setShippingType(ShippingTypeEnum.SH.getValue());
        header.setShippingStatus(ShippingStatusEnum.INIT.getValue());
        header.setShippingCode(WmsCodeGeneratorUtil.createShippingCode(warehouseId));
        header.setWarehouseId(warehouseId);
        if (!shippingHeaderService.save(header)) {
            throw new WmsServiceException("保存发运信息异常");
        }
        if (ListUtil.isNullOrEmpty(deliveryIds)) {
            throw new WmsServiceException("订单参数缺失");
        }
        long totalCount = header.getTotalCount();
        long totalBoxCount = header.getTotalBoxCount();
        long totalNoBoxCount = header.getTotalNoBoxCount();
        long realTotalCount = 0L;
        long realTotalBoxCount = 0L;
        long realTotalNoBoxCount = 0L;
        for (Long deliveryId : deliveryIds) {
            DeliveryOrderHeader orderHeader = deliveryOrderHeaderService.getById(deliveryId);
            if (orderHeader == null) {
                throw new WmsServiceException("该订单不存在");
            }
            if (!DeliveryOrderStatusEnum.PICKED.getValue().equals(orderHeader.getOrderStatus())) {
                throw new WmsServiceException("该订单状态不是已拣货");
            }
            Set<Long> boxIds = new HashSet<>();
            Long realCount = 0L;
            Long realBoxCount = 0L;
            Long realNoBoxCount = 0L;
            List<DeliveryOrderBox> deliveryOrderBoxes = deliveryOrderBoxService.getByOrderHeaderId(deliveryId);
            for (DeliveryOrderBox deliveryOrderBox : deliveryOrderBoxes) {
                long qty = deliveryOrderBox.getBoxQty().longValue();
                realCount += qty;
                if (-1L == deliveryOrderBox.getBoxId()) {
                    realNoBoxCount += qty;
                } else {
                    boxIds.add(deliveryOrderBox.getBoxId());
                }
            }
            realBoxCount = (long) boxIds.size();
            addShippingDetail(warehouseId,header,orderHeader,realCount,realBoxCount,realNoBoxCount);
            realTotalCount += realCount;
            realTotalBoxCount += realBoxCount;
            realTotalNoBoxCount += realNoBoxCount;
        }
        if(realTotalCount != totalCount || realTotalBoxCount != totalBoxCount || realTotalNoBoxCount != totalNoBoxCount){
            header.setTotalCount(realTotalCount);
            header.setTotalBoxCount(realTotalBoxCount);
            header.setTotalNoBoxCount(realTotalNoBoxCount);
            if (!shippingHeaderService.updateById(header)) {
                throw new WmsServiceException("更新统计数据异常");
            }
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addReturnShipping(ShippingHeader header, List<Long> returnHeaderIds, Long warehouseId, Integer userId) throws WmsServiceException {
        if (header == null) {
            throw new WmsServiceException("参数缺失");
        }
        String carOutCode = header.getCarOutCode();
        if (StringUtils.isNotEmpty(carOutCode)) {
            CarOut carOut = carOutService.getByCarOutCode(carOutCode);
            if (carOut == null) {
                throw new WmsServiceException("出车订单不存在");
            }
            if (!CarOutStatusEnum.INIT.getValue().equals(carOut.getCarOutStatus())) {
                throw new WmsServiceException("出车单已使用");
            }
            if (!CarOutTypeEnum.TH.getValue().equals(carOut.getCarOutType())) {
                throw new WmsServiceException("出车单类型不是提货");
            }
            header.setCarOutId(carOut.getId());
            carOut.setCarOutStatus(CarOutStatusEnum.WAIT_OUT.getValue());
            carOutService.updateById(carOut);
        }
        header.setShippingType(ShippingTypeEnum.TH.getValue());
        header.setShippingStatus(ShippingStatusEnum.INIT.getValue());
        header.setShippingCode(WmsCodeGeneratorUtil.createShippingCode(warehouseId));
        header.setWarehouseId(warehouseId);
        if (!shippingHeaderService.save(header)) {
            throw new WmsServiceException("保存发运信息异常");
        }
        if (ListUtil.isNullOrEmpty(returnHeaderIds)) {
            throw new WmsServiceException("退货单参数缺失");
        }
        long totalCount = header.getTotalCount();
        long totalBoxCount = header.getTotalBoxCount();
        long realTotalCount = 0L;
        long realTotalBoxCount = 0L;
        for (Long returnHeaderId : returnHeaderIds) {
            ReturnWarehouseHeader returnWarehouseHeader = returnWarehouseHeaderService.getById(returnHeaderId);
            if (returnWarehouseHeader == null) {
                throw new WmsServiceException("退货单不存在");
            }
            if (!ReturnStatusEnum.WAIT_RETURN.getValue().equals(returnWarehouseHeader.getReturnStatus())) {
                throw new WmsServiceException("退货单状态不是待提货");
            }
            realTotalBoxCount +=returnWarehouseHeader.getBoxCount();
            realTotalCount +=returnWarehouseHeader.getSkuCount();

            saveReturnShippingDetail(header, returnWarehouseHeader, warehouseId);
        }
        if(realTotalCount != totalCount || realTotalBoxCount != totalBoxCount){
            header.setTotalCount(realTotalCount);
            header.setTotalBoxCount(realTotalBoxCount);
            if (!shippingHeaderService.updateById(header)) {
                throw new WmsServiceException("更新统计数据异常");
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateShipping(ShippingHeader header, List<Long> deliveryIds, Long warehouseId, Integer userId) throws WmsServiceException {
        ShippingHeader shippingHeader = shippingHeaderService.getById(header.getId());
        if (shippingHeader == null) {
            throw new WmsServiceException("发运单不存在");
        }
        if (!ShippingStatusEnum.INIT.getValue().equals(shippingHeader.getShippingStatus())) {
            throw new WmsServiceException("非待发运的订单无法修改");
        }
        if (!ShippingTypeEnum.SH.getValue().equals(shippingHeader.getShippingType())) {
            throw new WmsServiceException("发运订单类型异常");
        }
        upShippingHeader(header, shippingHeader);
        if (ListUtil.isNullOrEmpty(deliveryIds)) {
            throw new WmsServiceException("订单参数缺失");
        }
        long realTotalCount = 0L;
        long realTotalBoxCount = 0L;
        long realTotalNoBoxCount = 0L;
        List<ShippingDetail> shippingDetails = shippingDetailService.getByHeaderId(shippingHeader.getId());
        for (ShippingDetail shippingDetail : shippingDetails) {
            DeliveryOrderHeader orderHeader = deliveryOrderHeaderService.getById(shippingDetail.getDeliveryHeaderId());
            if (orderHeader == null) {
                throw new WmsServiceException("订单不存在");
            }
            if (!DeliveryOrderStatusEnum.HANDOVER.getValue().equals(orderHeader.getOrderStatus())) {
                throw new WmsServiceException("订单状态不是已交接");
            }
            if(deliveryIds.contains(shippingDetail.getDeliveryHeaderId())){//已存在的旧明细
                deliveryIds.remove(shippingDetail.getDeliveryHeaderId());
                realTotalCount += shippingDetail.getSkuCount();
                realTotalBoxCount += shippingDetail.getBoxCount();
                realTotalNoBoxCount += shippingDetail.getNoBoxCount();
            }else {//删除的旧明细
                orderHeader.setOrderStatus(DeliveryOrderStatusEnum.PICKED.getValue());
                if (!deliveryOrderHeaderService.updateById(orderHeader)) {
                    throw new WmsServiceException("回退订单状态异常");
                }
                if (!shippingDetailService.removeById(shippingDetail.getId())) {
                    throw new WmsServiceException("清除多余明细异常");
                }
            }
        }
        for (Long deliveryId : deliveryIds) {//新增的明细
            DeliveryOrderHeader orderHeader = deliveryOrderHeaderService.getById(deliveryId);
            if (orderHeader == null) {
                throw new WmsServiceException("订单不存在");
            }
            if (!DeliveryOrderStatusEnum.PICKED.getValue().equals(orderHeader.getOrderStatus())) {
                throw new WmsServiceException("订单状态不是已拣货");
            }
            Set<Long> boxIds = new HashSet<>();
            Long realCount = 0L;
            Long realBoxCount = 0L;
            Long realNoBoxCount = 0L;
            List<DeliveryOrderBox> deliveryOrderBoxes = deliveryOrderBoxService.getByOrderHeaderId(deliveryId);
            for (DeliveryOrderBox deliveryOrderBox : deliveryOrderBoxes) {
                long qty = deliveryOrderBox.getBoxQty().longValue();
                realCount += qty;
                if (-1L == deliveryOrderBox.getBoxId()) {
                    realNoBoxCount += qty;
                } else {
                    boxIds.add(deliveryOrderBox.getBoxId());
                }
            }
            realBoxCount = (long) boxIds.size();
            addShippingDetail(warehouseId, shippingHeader, orderHeader, realCount, realBoxCount, realNoBoxCount);
            realTotalCount += realCount;
            realTotalBoxCount += realBoxCount;
            realTotalNoBoxCount += realNoBoxCount;
        }
        shippingHeader.setTotalCount(realTotalCount);
        shippingHeader.setTotalBoxCount(realTotalBoxCount);
        shippingHeader.setTotalNoBoxCount(realTotalNoBoxCount);
        if (!shippingHeaderService.updateById(shippingHeader)) {
            throw new WmsServiceException("更新发运异常");
        }
    }

    private void addShippingDetail(Long warehouseId, ShippingHeader shippingHeader, DeliveryOrderHeader orderHeader, Long realCount, Long realBoxCount, Long realNoBoxCount) throws WmsServiceException {
        ShippingDetail detail = new ShippingDetail();
        detail.setShippingHeaderId(shippingHeader.getId());
        detail.setShippingHeaderCode(shippingHeader.getShippingCode());
        detail.setDeliveryHeaderId(orderHeader.getId());
        detail.setDeliveryHeaderCode(orderHeader.getOrderCode());
        detail.setBoxCount(realBoxCount);
        detail.setSkuCount(realCount);
        detail.setNoBoxCount(realNoBoxCount);
        detail.setWarehouseId(warehouseId);
        if (!shippingDetailService.save(detail)) {
            throw new WmsServiceException("保存发运明细信息异常");
        }
        orderHeader.setOrderStatus(DeliveryOrderStatusEnum.HANDOVER.getValue());
        if (!deliveryOrderHeaderService.updateById(orderHeader)) {
            throw new WmsServiceException("更新订单交接异常");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateReturnShipping(ShippingHeader header, List<Long> deliveryIds, Long warehouseId, Integer userId) throws WmsServiceException {
        ShippingHeader shippingHeader = shippingHeaderService.getById(header.getId());
        if (shippingHeader == null) {
            throw new WmsServiceException("发运单不存在");
        }
        if (!ShippingStatusEnum.INIT.getValue().equals(shippingHeader.getShippingStatus())) {
            throw new WmsServiceException("非待发运的订单无法修改");
        }
        if (!ShippingTypeEnum.TH.getValue().equals(shippingHeader.getShippingType())) {
            throw new WmsServiceException("发运订单类型异常");
        }
        if (ListUtil.isNullOrEmpty(deliveryIds)) {
            throw new WmsServiceException("订单参数缺失");
        }
        upShippingHeader(header, shippingHeader);
        long realTotalCount = 0L;
        long realTotalBoxCount = 0L;
        List<ShippingDetail> shippingDetails = shippingDetailService.getByHeaderId(shippingHeader.getId());
        for (ShippingDetail shippingDetail : shippingDetails) {
            ReturnWarehouseHeader returnWarehouseHeader = returnWarehouseHeaderService.getById(shippingDetail.getDeliveryHeaderId());
            if (returnWarehouseHeader == null) {
                throw new WmsServiceException("订单不存在");
            }
            if (!ReturnStatusEnum.RETURNING.getValue().equals(returnWarehouseHeader.getReturnStatus())) {
                throw new WmsServiceException("订单状态不是提货中");
            }
            if(deliveryIds.contains(shippingDetail.getDeliveryHeaderId())){//已存在的旧明细
                deliveryIds.remove(shippingDetail.getDeliveryHeaderId());
                realTotalCount += shippingDetail.getSkuCount();
                realTotalBoxCount += shippingDetail.getBoxCount();
            }else {//删除的旧明细
                returnWarehouseHeader.setReturnStatus(ReturnStatusEnum.WAIT_RETURN.getValue());
                if (!returnWarehouseHeaderService.updateById(returnWarehouseHeader)) {
                    throw new WmsServiceException("回退订单状态异常");
                }
                if (!shippingDetailService.removeById(shippingDetail.getId())) {
                    throw new WmsServiceException("清除多余明细异常");
                }
            }
        }
        for (Long returnHeaderId : deliveryIds) {
            ReturnWarehouseHeader returnWarehouseHeader = returnWarehouseHeaderService.getById(returnHeaderId);
            if (returnWarehouseHeader == null) {
                throw new WmsServiceException("退货订单不存在");
            }
            if (!ReturnStatusEnum.WAIT_RETURN.getValue().equals(returnWarehouseHeader.getReturnStatus())) {
                throw new WmsServiceException("退货订单状态不是待提货");
            }
            realTotalBoxCount +=returnWarehouseHeader.getBoxCount();
            realTotalCount +=returnWarehouseHeader.getSkuCount();

            saveReturnShippingDetail(header, returnWarehouseHeader, warehouseId);
        }
        shippingHeader.setTotalCount(realTotalCount);
        shippingHeader.setTotalBoxCount(realTotalBoxCount);
        if (!shippingHeaderService.updateById(shippingHeader)) {
            throw new WmsServiceException("更新发运异常");
        }
    }

    private void saveReturnShippingDetail(ShippingHeader header, ReturnWarehouseHeader returnWarehouseHeader, Long warehouseId) throws WmsServiceException {
        ShippingDetail detail = new ShippingDetail();
        detail.setShippingHeaderId(header.getId());
        detail.setShippingHeaderCode(header.getShippingCode());
        detail.setDeliveryHeaderId(returnWarehouseHeader.getId());
        detail.setDeliveryHeaderCode(returnWarehouseHeader.getReturnCode());
        detail.setBoxCount(returnWarehouseHeader.getBoxCount());
        detail.setSkuCount(returnWarehouseHeader.getSkuCount());
        detail.setNoBoxCount(0L);
        detail.setWarehouseId(warehouseId);
        if (!shippingDetailService.save(detail)) {
            throw new WmsServiceException("保存发明细运信息异常");
        }
        returnWarehouseHeader.setReturnStatus(ReturnStatusEnum.RETURNING.getValue());
        if (!returnWarehouseHeaderService.updateById(returnWarehouseHeader)) {
            throw new WmsServiceException("更新退货单提货异常");
        }
    }

    private void upShippingHeader(ShippingHeader param, ShippingHeader shippingHeader) throws WmsServiceException {
        String carOutCode = param.getCarOutCode();
        String oldCarOutCode = shippingHeader.getCarOutCode();
        if (StringUtils.isNotEmpty(carOutCode)) {
            if(!carOutCode.equals(oldCarOutCode)){
                CarOut carOut = carOutService.getByCarOutCode(carOutCode);
                if (carOut == null) {
                    throw new WmsServiceException("出车单不存在");
                }
                if (!CarOutStatusEnum.INIT.getValue().equals(carOut.getCarOutStatus())) {
                    throw new WmsServiceException("出车单已使用");
                }
                if (ShippingTypeEnum.TH.getValue().equals(shippingHeader.getShippingType()) && !CarOutTypeEnum.TH.getValue().equals(carOut.getCarOutType())) {
                    throw new WmsServiceException("出车单类型不是提货");
                }
                if (ShippingTypeEnum.SH.getValue().equals(shippingHeader.getShippingType()) && !CarOutTypeEnum.SH.getValue().equals(carOut.getCarOutType())) {
                    throw new WmsServiceException("出车单类型不是送货");
                }
                carOut.setCarOutStatus(CarOutStatusEnum.WAIT_OUT.getValue());
                carOutService.updateById(carOut);
                shippingHeader.setCarOutId(carOut.getId());
                shippingHeader.setCarOutCode(carOut.getCarOutCode());
                //旧单回退
                if(StringUtils.isNotEmpty(oldCarOutCode)){
                    CarOut old = carOutService.getByCarOutCode(oldCarOutCode);
                    old.setCarOutStatus(CarOutStatusEnum.INIT.getValue());
                    carOutService.updateById(old);
                }
            }
        }else {//删除了出车单，旧单回退
            shippingHeader.setCarOutId(null);
            shippingHeader.setCarOutCode(null);
            if(StringUtils.isNotEmpty(oldCarOutCode)){
                CarOut carOut = carOutService.getByCarOutCode(oldCarOutCode);
                carOut.setCarOutStatus(CarOutStatusEnum.INIT.getValue());
                carOutService.updateById(carOut);
            }
        }
        shippingHeader.setAddress(param.getAddress());
        shippingHeader.setCarNumber(param.getCarNumber());
        shippingHeader.setCarrierName(param.getCarrierName());
        shippingHeader.setTrackingNumber(param.getTrackingNumber());
        shippingHeader.setConcatName(param.getConcatName());
        shippingHeader.setConcatTel(param.getConcatTel());
        shippingHeader.setDriverId(param.getDriverId());
        shippingHeader.setDriverName(param.getDriverName());
        shippingHeader.setDriverTel(param.getDriverTel());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void batchStartShipping(List<Long> ids, Long warehouseId, Integer sysUserId) throws WmsServiceException {
        if (ListUtil.isNullOrEmpty(ids)) {
            throw new WmsServiceException("参数缺失");
        }
        for (Long id : ids) {
            startShipping(id,warehouseId,sysUserId);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void batchStartReturnShipping(List<Long> ids, Long warehouseId, Integer userId) throws WmsServiceException {
        if (ListUtil.isNullOrEmpty(ids)) {
            throw new WmsServiceException("参数缺失");
        }
        for (Long id : ids) {
            startReturnShipping(id,warehouseId,userId);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void startShipping(Long shippingId, Long warehouseId, Integer userId) throws WmsServiceException {
        ShippingHeader shippingHeader = shippingHeaderService.getById(shippingId);
        if (shippingHeader == null) {
            throw new WmsServiceException("发运单不存在");
        }
        if (!ShippingStatusEnum.INIT.getValue().equals(shippingHeader.getShippingStatus())) {
            throw new WmsServiceException("发运单已发运");
        }
        //扣减拣货库存
        List<ShippingDetail> details = shippingDetailService.getByHeaderId(shippingId);
        if (ListUtil.isNullOrEmpty(details)) {
            throw new WmsServiceException("明细不存在");
        }
//        List<DeliveryOrderDetail> deliveryOrderDetails = new ArrayList<>();
        for (ShippingDetail detail : details) {
            DeliveryOrderHeader orderHeader = deliveryOrderHeaderService.getById(detail.getDeliveryHeaderId());
            if (orderHeader == null) {
                throw new WmsServiceException("订单不存在");
            }
            if (!DeliveryOrderStatusEnum.HANDOVER.getValue().equals(orderHeader.getOrderStatus())) {
                throw new WmsServiceException("订单状态不是已交接");
            }
            orderHeader.setOrderStatus(DeliveryOrderStatusEnum.OUT.getValue());
            if (!deliveryOrderHeaderService.updateById(orderHeader)) {
                throw new WmsServiceException("更新订单出库异常");
            }
//            deliveryOrderDetails.addAll(deliveryOrderDetailService.getByHeaderId(detail.getDeliveryHeaderId()));
            List<CodeHolderPoint> points = codeHolderPointService.getByCurDocId(orderHeader.getId());
            if (ListUtil.isNotEmpty(points)) {//释放码托占用
                for (CodeHolderPoint point : points) {
                    point.setPointStatus(PointStatusEnum.FREE.getValue());
                    point.setCurDocId(null);
                    point.setCurShopId(null);
                    codeHolderPointService.updateById(point);
                }
            }
        }
//        deliveryOrderDetails.sort(Comparator.comparing(DeliveryOrderDetail::getSkuId));
//        for (DeliveryOrderDetail orderDetail : deliveryOrderDetails) {
//            Sku sku = skuService.getByIdForReal(orderDetail.getSkuId());
//            if (sku == null) {
//                sku = new Sku();
//                sku.setId(orderDetail.getSkuId());
//                sku.setBarcode("none-"+orderDetail.getSkuId());
//                sku.setSkuCode("none-"+orderDetail.getSkuId());
//            }
//            BigDecimal needSubQty = BigDecimal.valueOf(orderDetail.getSendQty());
//            if (needSubQty.compareTo(BigDecimal.ZERO) == 0) {//未拣货
//                continue;
//            }
//            List<StockPick> stockPickList = stockPickService.getBySkuId(orderDetail.getSkuId());
//            if (ListUtil.isNullOrEmpty(stockPickList)) {
//                throw new WmsServiceException("拣货库存未找到该商品:商品编码:" + sku.getSkuCode()+"商品编条码:"+sku.getBarcode());
//            }
//            BigDecimal totalQty = stockPickList.stream().map(StockPick::getPickQty).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
//            if (totalQty.compareTo(needSubQty) < 0) {
//                throw new WmsServiceException("拣货库存不足：商品编码:" + sku.getSkuCode()+"商品编条码:"+sku.getBarcode());
//            }
//            for (StockPick stockPick : stockPickList) {
//                if (needSubQty.compareTo(BigDecimal.ZERO) == 0) {//扣减结束
//                    break;
//                }
//                if (stockPick.getPickQty().compareTo(needSubQty) >= 0) {
//                    //扣减主库存
//                    StockChangeDto stockChangeDto = new StockChangeDto();
//                    stockChangeDto.setSkuId(orderDetail.getSkuId());
//                    stockChangeDto.setBatchId(stockPick.getBatchId());
////                    stockChangeDto.setToBatchId(WmsConstans.DEF_BATCH_ID);
//                    stockChangeDto.setQty(needSubQty);
//                    stockChangeDto.setLocId(stockPick.getLocId());
//                    stockChangeDto.setWarehouseId(warehouseId);
//                    stockChangeDto.setUserId(userId);
//                    stockChangeDto.setStockId(stockPick.getId());
//                    stockChangeDto = wmsStockFacade.subPickStock(stockChangeDto);
//                    needSubQty = BigDecimal.ZERO;
//                } else {
//                    //扣减主库存
//                    StockChangeDto stockChangeDto = new StockChangeDto();
//                    stockChangeDto.setSkuId(orderDetail.getSkuId());
//                    stockChangeDto.setBatchId(stockPick.getBatchId());
////                    stockChangeDto.setToBatchId(WmsConstans.DEF_BATCH_ID);
//                    stockChangeDto.setQty(stockPick.getPickQty());
//                    stockChangeDto.setWarehouseId(warehouseId);
//                    stockChangeDto.setUserId(userId);
//                    stockChangeDto.setStockId(stockPick.getId());
//                    stockChangeDto = wmsStockFacade.subPickStock(stockChangeDto);
//                    needSubQty = needSubQty.subtract(stockPick.getPickQty());
//                }
//            }
//            if (needSubQty.compareTo(BigDecimal.ZERO) > 0) {
//                throw new WmsServiceException("拣货库存不足：商品编码:" + sku.getSkuCode()+"商品编条码:"+sku.getBarcode());
//            }
//        }
        confirmSendCar(shippingHeader);
        shippingHeader.setShippingStatus(ShippingStatusEnum.SEND.getValue());
        if (!shippingHeaderService.updateById(shippingHeader)) {
            throw new WmsServiceException("更新发运异常");
        }

    }

    private void confirmSendCar(ShippingHeader shippingHeader) throws WmsServiceException {
        if(shippingHeader.getCarOutId() != null){
            CarOut carOut = carOutService.getById(shippingHeader.getCarOutId());
            if (carOut == null) {
                throw new WmsServiceException("出车单数据未找到");
            }
            carOut.setCarOutStatus(CarOutStatusEnum.OUT.getValue());
            carOutService.updateById(carOut);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void startReturnShipping(Long shippingId, Long warehouseId, Integer userId) throws WmsServiceException {
        ShippingHeader shippingHeader = shippingHeaderService.getById(shippingId);
        if (shippingHeader == null) {
            throw new WmsServiceException("发运单不存在");
        }
        if (!ShippingStatusEnum.INIT.getValue().equals(shippingHeader.getShippingStatus())) {
            throw new WmsServiceException("发运单已发运");
        }
        confirmSendCar(shippingHeader);
        shippingHeader.setShippingStatus(ShippingStatusEnum.SEND.getValue());
        if (!shippingHeaderService.updateById(shippingHeader)) {
            throw new WmsServiceException("更新发运异常");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void completedShipping(Long shippingId, Long warehouseId, Integer userId) throws WmsServiceException {

    }
}
